package io.rong.app;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.yunshipei.base.EnterBaseSubscriber;
import com.yunshipei.common.Globals;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.manager.EnterplorerNotificationManager;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.ClearDeviceEventBuilder;
import com.yunshipei.model.ClearGroupNumber;
import com.yunshipei.model.EventModelObject;
import com.yunshipei.model.QuitGroupModel;
import com.yunshipei.model.UserInfo;
import com.yunshipei.model.YspEvent;
import com.yunshipei.model.YspEvent.StartBrowserEvent;
import com.yunshipei.ui.activity.DetailContactsActivity;
import com.yunshipei.ui.activity.SeekContactsActivity;
import com.yunshipei.utils.StringUtil;
import com.yunshipei.utils.YspProtocolUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import io.rong.app.activity.NewFriendListActivity;
import io.rong.app.activity.RealTimeLocationActivity;
import io.rong.app.model.GroupCreateInfo;
import io.rong.app.ui.WinToast;
import io.rong.app.utils.StringUtilSub;
import io.rong.eventbus.EventBus;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.mention.IMentionedInputListener;
import io.rong.imkit.mention.RongMentionManager;
import io.rong.imkit.model.Event;
import io.rong.imkit.model.UIConversation;
import io.rong.imkit.widget.AlterDialogFragment;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.location.RealTimeLocationConstant;
import io.rong.imlib.location.message.RealTimeLocationStartMessage;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.message.CommandNotificationMessage;
import io.rong.message.ContactNotificationMessage;
import io.rong.message.FileMessage;
import io.rong.message.ImageMessage;
import io.rong.message.InformationNotificationMessage;
import io.rong.message.LocationMessage;
import io.rong.message.RichContentMessage;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;

/**
 * 融云SDK事件监听处理。
 * 把事件统一处理，开发者可直接复制到自己的项目中去使用。
 * <p/>
 * 该类包含的监听事件有：
 * 1、消息接收器：OnReceiveMessageListener。O
 * 2、发出消息接收器：OnSendMessageListener。
 * 3、用户信息提供者：GetUserInfoProvider。
 * 4、好友信息提供者：GetFriendsProvider。
 * 5、群组信息提供者：GetGroupInfoProvider。
 * 7、连接状态监听器，以获取连接相关状态：ConnectionStatusListener。
 * 8、地理位置提供者：LocationProvider。
 * 9、自定义 push 通知： OnReceivePushMessageListener。
 * RongIMClient.OnReceivePushMessageListener
 * 10、会话列表界面操作的监听器：ConversationListBehaviorListener。
 */
public final class RongCloudEvent implements RongIMClient.OnReceiveMessageListener, RongIM.OnSendMessageListener,
        RongIM.UserInfoProvider, RongIM.GroupInfoProvider, RongIM.ConversationBehaviorListener,
        RongIMClient.ConnectionStatusListener, RongIM.LocationProvider, RongIM.ConversationListBehaviorListener,
        Handler.Callback, IMentionedInputListener {

    private static final String TAG = RongCloudEvent.class.getSimpleName();
    private static RongCloudEvent mRongCloudInstance;
    private Context mContext;
    private DatabaseUtil databaseUtil = null;
    private static SharedPreferences mySharedPreferences = null;

    /**
     * 初始化 RongCloud.
     *
     * @param context 上下文。
     */
    public static void init(Context context) {
        mySharedPreferences = YspPreferences.getInstance().getSharedPreferences();

        if (mRongCloudInstance == null) {

            synchronized (RongCloudEvent.class) {

                if (mRongCloudInstance == null) {
                    mRongCloudInstance = new RongCloudEvent(context);
                }
            }
        }
    }

    /**
     * 构造方法。
     *
     * @param context 上下文。
     */
    private RongCloudEvent(Context context) {
        mContext = context;
        initDefaultListener();
        setOtherListener();
    }

    /**
     * RongIM.init(this) 后直接可注册的Listener。
     */
    private void initDefaultListener() {
        databaseUtil = new DatabaseUtil();
        RongIM.setUserInfoProvider(this, true);                 //设置用户信息提供者。
        RongIM.setGroupInfoProvider(this, true);                //设置群组信息提供者。
        RongIM.setConversationBehaviorListener(this);           //设置会话界面操作的监听器。
//        RongIM.setLocationProvider(this);                       //设置地理位置提供者,不用位置的同学可以注掉此行代码
        RongIM.getInstance().setMessageAttachedUserInfo(true);  //消息体内是否有 userinfo 这个属性
        RongIM.setConversationListBehaviorListener(this);
        //消息阅读回执 支持的会话类型
        RongIM.getInstance().setReadReceiptConversationTypeList(new Conversation.ConversationType[]{
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP,
                Conversation.ConversationType.DISCUSSION
        });
    }

    /*
     * 连接成功注册。
     * <p/>
     * 在RongIM-connect-onSuccess后调用。
     */
    public void setOtherListener() {
        RongIM.getInstance().setOnReceiveMessageListener(this);     //设置消息接收监听器。
        RongIM.getInstance().setConnectionStatusListener(this);     //设置连接状态监听器。
        RongIM.getInstance().setSendMessageListener(this);          //设置发出消息接收监听器.
        RongMentionManager.getInstance().setMentionedInputListener(this);       //@输入监听
    }

    /**
     * 获取RongCloud 实例。
     *
     * @return RongCloud。
     */
    public static RongCloudEvent getInstance() {
        return mRongCloudInstance;
    }

    /**
     * 接收消息的监听器：OnReceiveMessageListener 的回调方法，接收到消息后执行。
     *
     * @param message 接收到的消息的实体信息。
     * @param left    剩余未拉取消息数目。
     */
    @Override
    public boolean onReceived(final Message message, int left) {
        final MessageContent messageContent = message.getContent();
        if (messageContent instanceof TextMessage) {//文本消息
            TextMessage textMessage = (TextMessage) messageContent;
            textMessage.getExtra();
            Log.d(TAG, "onReceived-TextMessage:" + textMessage.getContent());
        } else if (messageContent instanceof ImageMessage) {//图片消息
            ImageMessage imageMessage = (ImageMessage) messageContent;
            Log.d(TAG, "onReceived-ImageMessage:" + imageMessage.getRemoteUri());
        } else if (messageContent instanceof VoiceMessage) {//语音消息
            VoiceMessage voiceMessage = (VoiceMessage) messageContent;
            Log.d(TAG, "onReceived-voiceMessage:" + voiceMessage.getUri().toString());
        } else if (messageContent instanceof RichContentMessage) {//图文消息
            RichContentMessage richContentMessage = (RichContentMessage) messageContent;
            Log.d(TAG, "onReceived-RichContentMessage:" + richContentMessage.getContent());
        } else if (messageContent instanceof InformationNotificationMessage) {//小灰条消息
            InformationNotificationMessage informationNotificationMessage = (InformationNotificationMessage) messageContent;
            Log.d(TAG, "onReceived-informationNotificationMessage:" + informationNotificationMessage.getMessage());
            handlerINMessage(message.getConversationType(), message.getTargetId(), informationNotificationMessage);
        } else if (messageContent instanceof CommandNotificationMessage) {
            CommandNotificationMessage commandNotificationMessage = (CommandNotificationMessage) messageContent;
            if (commandNotificationMessage.getName().contains("ysp_clear")) {
                try {
                    JSONObject jsonData = new JSONObject(commandNotificationMessage.getData());
                    EventBus.getDefault().post(new ClearDeviceEventBuilder().setDeviceId(jsonData.optString("deviceId", "")).setGUID(jsonData.optString("GUID", ""))
                            .setMessageData(jsonData.optString("timestamp", "")).setMessageName("ysp_clear").build());
                    return true;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else if (messageContent instanceof FileMessage) {
            FileMessage fileMessage = (FileMessage) messageContent;
            Log.e("FileMessage", fileMessage.getMediaUrl() + fileMessage.getName() + "\n" + fileMessage.getLocalPath());
        } else {
            Log.d(TAG, "onReceived-其他消息，自己来判断处理");
        }
        RongIMClient.getInstance().getConversationNotificationStatus(message.getConversationType(), message.getTargetId(), new RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
            @Override
            public void onSuccess(Conversation.ConversationNotificationStatus cns) {
                boolean sound = false;
                if ((System.currentTimeMillis() - currentTimeMinutes) > 5 * 1000) {
                    currentTimeMinutes = System.currentTimeMillis();
                    sound = true;
                }
                if (cns != null && cns == Conversation.ConversationNotificationStatus.NOTIFY) {
                    new EnterplorerNotificationManager.Builder().setContext(mContext).setSound(sound).build().showNotification(message);
                } else if (StringUtilSub.checkExtra(messageContent instanceof TextMessage ?
                        ((TextMessage) messageContent).getExtra() : "")) {
                    new EnterplorerNotificationManager.Builder().setContext(mContext).setSound(sound).build().showNotification(message);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
        return true;
    }

    private long currentTimeMinutes = 0;

    /**
     * 小灰条消息处理
     *
     * @param informationNotificationMessage
     */
    private void handlerINMessage(Conversation.ConversationType conversationType,
                                  String targetId, InformationNotificationMessage informationNotificationMessage) {
        if (informationNotificationMessage != null) {
            String extra = informationNotificationMessage.getExtra();
            if (TextUtils.isEmpty(extra))
                return;
            try {
                JSONObject extraJson = new JSONObject(extra);
                String action = extraJson.getString("action");
                String groupId = extraJson.getString("groupId");
                if ("joinGroup".equals(action)) {
                    joinGroup(extraJson, groupId);
                } else if ("quitGroup".equals(action)) {
//                    quitGroup(conversationType, targetId, extraJson, groupId);
                    quitGroupNew(conversationType, targetId, extraJson, groupId);
                } else if ("editGroup".equals(action)) {
                    editGroup(extraJson, groupId);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 添加了用户缓存更新方法(rongcloud)
     */
    private void refreshGroupInfo(Group group) {
        if (group == null) {
            throw new IllegalArgumentException();
        }
        if (RongIM.getInstance() != null) {
            RongIM.getInstance().refreshGroupInfoCache(group);
        }
    }

    @Override
    public Message onSend(Message message) {
        return message;
    }

    /**
     * 消息在UI展示后执行/自己的消息发出后执行,无论成功或失败。
     *
     * @param message 消息。
     */
    @Override
    public boolean onSent(Message message, RongIM.SentMessageErrorCode sentMessageErrorCode) {

        if (message.getSentStatus() == Message.SentStatus.FAILED) {

            if (sentMessageErrorCode == RongIM.SentMessageErrorCode.NOT_IN_GROUP) {//不在群组

            } else if (sentMessageErrorCode == RongIM.SentMessageErrorCode.REJECTED_BY_BLACKLIST) {//你在他的黑名单中
                WinToast.toast(mContext, "你在对方的黑名单中");
            }
        }
        MessageContent messageContent = message.getContent();
        if (messageContent instanceof TextMessage) {//文本消息
            TextMessage textMessage = (TextMessage) messageContent;
            Log.d(TAG, "onSent-TextMessage:" + textMessage.getContent());
        } else if (messageContent instanceof ImageMessage) {//图片消息
            ImageMessage imageMessage = (ImageMessage) messageContent;
            Log.d(TAG, "onSent-ImageMessage:" + imageMessage.getRemoteUri());
        } else if (messageContent instanceof VoiceMessage) {//语音消息
            VoiceMessage voiceMessage = (VoiceMessage) messageContent;
            Log.d(TAG, "onSent-voiceMessage:" + voiceMessage.getUri().toString());
        } else if (messageContent instanceof RichContentMessage) {//图文消息
            RichContentMessage richContentMessage = (RichContentMessage) messageContent;
            Log.d(TAG, "onSent-RichContentMessage:" + richContentMessage.getContent());
        } else {
            Log.d(TAG, "onSent-其他消息，自己来判断处理");
        }
        return false;
    }

    /**
     * 用户信息的提供者：GetUserInfoProvider 的回调方法，获取用户信息。
     *
     * @param userId 用户 Id。
     * @return 用户信息，（注：由开发者提供用户信息）。
     */
    @Override
    public io.rong.imlib.model.UserInfo getUserInfo(String userId) {

        io.rong.imlib.model.UserInfo userInfo;
        if (!TextUtils.isEmpty(userId)) {

            userInfo = new DatabaseUtil().queryByUuid(userId);
            if (userInfo == null) {
                HttpMethods.getInstance().getUserInfoById(mySharedPreferences.getString("companyId", ""), userId, new UserInfoSubscriber());
            }

            return userInfo;
        }
        Log.e("getUserInfo", " userInfo is null");
        return null;
    }

    /**
     * 群组信息的提供者：GetGroupInfoProvider 的回调方法， 获取群组信息。
     *
     * @param groupId 群组 Id.
     * @return 群组信息，（注：由开发者提供群组信息）。
     */
    @Override
    public Group getGroupInfo(String groupId) {
        /**
         * demo 代码  开发者需替换成自己的代码。
         */
        Group group = null;
//        if (DemoContext.getInstance().getGroupMap() != null) {
//            group = DemoContext.getInstance().getGroupMap().get(groupId);
//        }
        if (group == null) {
            GroupCreateInfo groupCreateInfo = databaseUtil.findGroupById(groupId);
            if (groupCreateInfo != null) {
                if (!TextUtils.isEmpty(groupCreateInfo.getPortraitUri())) {
                    group = new Group(groupId, groupCreateInfo.getName(), Uri.parse(groupCreateInfo.getPortraitUri()));
                } else {
                    group = new Group(groupId, groupCreateInfo.getName(), Uri.parse(groupCreateInfo.getPortraitUri()));
                }
                return group;
            } else {
                HttpMethods.getInstance().fetchGroupById(groupId, new GroupInfoSubscriber());
            }
        }
        return group;
    }

    /**
     * 会话界面操作的监听器：ConversationBehaviorListener 的回调方法，当点击用户头像后执行。
     *
     * @param context          应用当前上下文。
     * @param conversationType 会话类型。
     * @param user             被点击的用户的信息。
     * @return 返回True不执行后续SDK操作，返回False继续执行SDK操作。
     */
    @Override
    public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, io.rong.imlib.model.UserInfo user) {
        Log.e(TAG, "----onUserPortraitClick");
        UserInfo userInfo = new DatabaseUtil().queryUserInfoByid(user.getUserId());
        if (userInfo != null) {
            Intent intent = new Intent();
            intent.setClass(context, DetailContactsActivity.class);
            intent.putExtra("userInfo", userInfo);
            context.startActivity(intent);
        }
        return true;
    }

    @Override
    public boolean onUserPortraitLongClick(final Context context, Conversation.ConversationType conversationType, io.rong.imlib.model.UserInfo userInfo) {
//        if (userInfo != null && !userInfo.getUserId().equals(mySharedPreferences.getString("uuid", ""))) {
//            EventBus.getDefault().post(new YspEvent.ATEvent(userInfo, ""));
//            return true;
//        }
//        ((Activity) context).runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                Toast.makeText(context.getApplicationContext(), "不能@自己", Toast.LENGTH_SHORT).show();
//            }
//        });
        return false;
    }

    /**
     * 会话界面操作的监听器：ConversationBehaviorListener 的回调方法，当点击消息时执行。
     *
     * @param context 应用当前上下文。
     * @param message 被点击的消息的实体信息。
     * @return 返回True不执行后续SDK操作，返回False继续执行SDK操作。
     */
    @Override
    public boolean onMessageClick(final Context context, final View view, final Message message) {
        Log.e(TAG, "----onMessageClick");

        if (message.getContent() instanceof RealTimeLocationStartMessage) {
            RealTimeLocationConstant.RealTimeLocationStatus status = RongIMClient.getInstance().getRealTimeLocationCurrentState(message.getConversationType(), message.getTargetId());
            if (status == RealTimeLocationConstant.RealTimeLocationStatus.RC_REAL_TIME_LOCATION_STATUS_INCOMING) {


                final AlterDialogFragment alterDialogFragment = AlterDialogFragment.newInstance("", "加入位置共享", "取消", "加入");
                alterDialogFragment.setOnAlterDialogBtnListener(new AlterDialogFragment.AlterDialogBtnListener() {

                    @Override
                    public void onDialogPositiveClick(AlterDialogFragment dialog) {
                        RealTimeLocationConstant.RealTimeLocationStatus status = RongIMClient.getInstance().getRealTimeLocationCurrentState(message.getConversationType(), message.getTargetId());
                        if (status == null || status == RealTimeLocationConstant.RealTimeLocationStatus.RC_REAL_TIME_LOCATION_STATUS_IDLE) {
                            startRealTimeLocation(context, message.getConversationType(), message.getTargetId());
                        } else {
                            joinRealTimeLocation(context, message.getConversationType(), message.getTargetId());
                        }
                    }

                    @Override
                    public void onDialogNegativeClick(AlterDialogFragment dialog) {
                        alterDialogFragment.dismiss();
                    }
                });

                alterDialogFragment.show(((FragmentActivity) context).getSupportFragmentManager());
            } else {
//                if (status != null && (status == RealTimeLocationConstant.RealTimeLocationStatus.RC_REAL_TIME_LOCATION_STATUS_OUTGOING || status == RealTimeLocationConstant.RealTimeLocationStatus.RC_REAL_TIME_LOCATION_STATUS_CONNECTED)) {
//                    Intent intent = new Intent(((FragmentActivity) context), RealTimeLocationActivity.class);
//                    intent.putExtra("conversationType", message.getConversationType().getValue());
//                    intent.putExtra("targetId", message.getTargetId());
//                    context.startActivity(intent);
//                }
            }
            return true;
        }
        //real-time location message end
        /**
         * demo 代码  开发者需替换成自己的代码。
         */
        if (message.getContent() instanceof LocationMessage) {
//            Intent intent = new Intent(context, LocationMapActivity.class);
//            intent.putExtra("location", message.getContent());
//            context.startActivity(intent);
            return false;
        } else if (message.getContent() instanceof RichContentMessage) {
            RichContentMessage mRichContentMessage = (RichContentMessage) message.getContent();
            if (!TextUtils.isEmpty(mRichContentMessage.getExtra())) {
                final String urlStr = mRichContentMessage.getExtra();
                EventBus.getDefault().post(new StartBrowserEvent(urlStr));
            } else {
                String url = ((RichContentMessage) message.getContent()).getUrl();
                EventBus.getDefault().post(new StartBrowserEvent(url));
            }
            return true;
        } else if (message.getContent() instanceof TextMessage) {
            /**
             * ((TextMessage) message.getContent()).getContent()获取到的就是消息内容
             * 你在这里判断一下 如果是我们添加的相关enterplorer://的相关处理就return true,
             * 否则 return false.
             */
            String content = ((TextMessage) message.getContent()).getContent();
            if (!StringUtil.isEmpty(((TextMessage) message.getContent()).getExtra())
                    && Globals.IM_MESSAGE_CONTACT.equals(((TextMessage) message.getContent()).getExtra())) {
                YspProtocolUtils.ringUp(mContext, "tel:" + content.substring(content.indexOf("\n"), content.length()));
                return true;
            }
        }
//        else if (message.getContent() instanceof FileMessage) {
//            Uri uri = ((FileMessage) message.getContent()).getMediaUrl();
//            EventBus.getDefault().post(new StartBrowserEvent(uri.toString()));
//        }
        Log.d("Begavior", message.getObjectName() + ":" + message.getMessageId());
        return false;
    }

    private void startRealTimeLocation(Context context, Conversation.ConversationType conversationType, String targetId) {
        RongIMClient.getInstance().startRealTimeLocation(conversationType, targetId);
        Intent intent = new Intent(((FragmentActivity) context), RealTimeLocationActivity.class);
        intent.putExtra("conversationType", conversationType.getValue());
        intent.putExtra("targetId", targetId);
        context.startActivity(intent);
    }

    private void joinRealTimeLocation(Context context, Conversation.ConversationType conversationType, String targetId) {
        RongIMClient.getInstance().joinRealTimeLocation(conversationType, targetId);
        Intent intent = new Intent(((FragmentActivity) context), RealTimeLocationActivity.class);
        intent.putExtra("conversationType", conversationType.getValue());
        intent.putExtra("targetId", targetId);
        context.startActivity(intent);
    }

    /**
     * 当点击链接消息时执行。
     *
     * @param context 上下文。
     * @param link    被点击的链接。
     * @return 如果用户自己处理了点击后的逻辑处理，则返回 true， 否则返回 false, false 走融云默认处理方式。
     */
    @Override
    public boolean onMessageLinkClick(Context context, String link) {
        if (StringUtilSub.isTelPhoneLink(link)) {
            YspProtocolUtils.ringUp(context, link);
        } else if (StringUtilSub.isEmailLink(link.substring(7, link.length()))) {
            YspProtocolUtils.openEmailClient(context, link);
        } else if (StringUtilSub.isNetWorkAddr(link)) {
            //打开浏览器
            EventBus.getDefault().post(new StartBrowserEvent(link));
        }
        return true;
    }

    @Override
    public boolean onMessageLongClick(Context context, View view, Message message) {
        Log.e(TAG, "----onMessageLongClick");
        return false;
    }

    /**
     * 连接状态监听器，以获取连接相关状态:ConnectionStatusListener 的回调方法，网络状态变化时执行。
     *
     * @param status 网络状态。
     */
    @Override
    public void onChanged(ConnectionStatus status) {
        Log.d(TAG, "onChanged " + status);
        if (status.getMessage().equals(ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT.getMessage())) {
            Log.e(TAG, "账户在其他设备登陆");
            EventBus.getDefault().post(status);
        }
    }

    /**
     * 位置信息提供者:LocationProvider 的回调方法，打开第三方地图页面。
     *
     * @param context  上下文
     * @param callback 回调
     */
    @Override
    public void onStartLocation(Context context, LocationCallback callback) {
        //         demo 代码  开发者需替换成自己的代码。
//        DemoContext.getInstance().setLastLocationCallback(callback);
//        Intent intent = new Intent(context, LocationMapActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.startActivity(intent);//SOSO地图
    }

    /**
     * 点击会话列表 item 后执行。
     *
     * @param context      上下文。
     * @param view         触发点击的 View。
     * @param conversation 会话条目。
     * @return 返回 true 不再执行融云 SDK 逻辑，返回 false 先执行融云 SDK 逻辑再执行该方法。
     */
    @Override
    public boolean onConversationClick(Context context, View view, UIConversation conversation) {
        MessageContent messageContent = conversation.getMessageContent();
        if (messageContent instanceof TextMessage) {//文本消息
            TextMessage textMessage = (TextMessage) messageContent;
            String extraStr = textMessage.getExtra();
        } else if (messageContent instanceof ContactNotificationMessage) {
            Log.e(TAG, "---onConversationClick--ContactNotificationMessage-");
            context.startActivity(new Intent(context, NewFriendListActivity.class));
            return true;
        }
        return false;
    }

    @Override
    public boolean onConversationPortraitClick(Context context, Conversation.ConversationType conversationType, String targetId) {
        return false;
    }

    @Override
    public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String targetId) {
        return false;
    }

    /**
     * 长按会话列表 item 后执行。
     *
     * @param context      上下文。
     * @param view         触发点击的 View。
     * @param conversation 长按会话条目。
     * @return 返回 true 不再执行融云 SDK 逻辑，返回 false 先执行融云 SDK 逻辑再执行该方法。
     */
    @Override
    public boolean onConversationLongClick(Context context, View view, UIConversation conversation) {
        return false;
    }


    @Override
    public boolean handleMessage(android.os.Message message) {
        return false;
    }


    @Override
    public boolean onMentionedInput(Conversation.ConversationType conversationType, String targetId) {
        GroupCreateInfo groupCreateInfo = DemoContext.getInstance().getOneResult(targetId);
        Intent seekIntent = new Intent(Globals.AT);
        seekIntent.putExtra("groupAcount", groupCreateInfo.getNumber());
        seekIntent.putExtra("groupMembers", groupCreateInfo.getGourpMembers());
        seekIntent.setClass(mContext, SeekContactsActivity.class);
        seekIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(seekIntent);
        return true;
    }

    private class UserInfoSubscriber extends EnterBaseSubscriber {

        @Override
        public void onSuccess(JSONObject resultObj) {
            UserInfo userInfo = new UserInfo();
            userInfo.setUuid(resultObj.optString("uuid", ""));
            userInfo.setName(resultObj.optString("name", ""));
            userInfo.setAvatar(resultObj.optString("avatar", ""));
            userInfo.setCompanyId(resultObj.optString("companyId", ""));
            userInfo.setCreatedTime(resultObj.optString("createTime", ""));
            userInfo.setDepartment(resultObj.optString("department", ""));
            userInfo.setDepartmentId(resultObj.optString("departmentId", ""));
            userInfo.setEmail(resultObj.optString("email", ""));
            userInfo.setIsAdmin(resultObj.optString("isAdmin", ""));
            userInfo.setPosition(resultObj.optString("position", ""));
            userInfo.setTel(resultObj.optString("tel", ""));
            userInfo.setPassword("");
            databaseUtil.Insert(userInfo);
            EventBus.getDefault().post(new YspEvent.RefreshMainAdapterEvent());
        }
    }

    private class GroupInfoSubscriber extends EnterBaseSubscriber {
        @Override
        public void onSuccess(JSONObject data) {
            try {
                GroupCreateInfo groupCreateInfo = StringUtilSub.SqlToObj(data);
                Group group;
                if (!TextUtils.isEmpty(groupCreateInfo.getPortraitUri())) {
                    group = new Group(groupCreateInfo.getId(), groupCreateInfo.getName(), Uri.parse(groupCreateInfo.getPortraitUri()));
                } else {
                    group = new Group(groupCreateInfo.getId(), groupCreateInfo.getName(), null);
                }
                if (DemoContext.getInstance() != null) {
                    DemoContext.getInstance().addGroupCreateInfo(groupCreateInfo);
                    Map<String, Group> map = new HashMap<>();
                    map.put(groupCreateInfo.getId(), group);
                    DemoContext.getInstance().addInfoGroupMap(map);
                }
                databaseUtil.updateOrInsertGroups(groupCreateInfo);
                EventBus.getDefault().post(new YspEvent.RefreshMainAdapterEvent());
                if (DemoContext.getInstance().getGroupMap().size() >= 0) {
                    EventBus.getDefault().post(new YspEvent.RefreshMainAdapterEvent());
                    EventBus.getDefault().post(group);
                    List<Group> list = new ArrayList<>(DemoContext.getInstance().getGroupMap().values());
                    RongIM.getInstance().getRongIMClient().syncGroup(list, new RongIMClient.OperationCallback() {
                        @Override
                        public void onSuccess() {
                            Log.d("syncGroup", "Rong Sync Group");
                            EventBus.getDefault().post(new YspEvent.RefreshMainAdapterEvent());
                        }

                        @Override
                        public void onError(RongIMClient.ErrorCode errorCode) {
                            Log.d("syncGroup status", "***** --- on Error --- *****");
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(String errorMsg) {
            Log.e("getGrouInfoByID", "    onFailure       ");
        }
    }

    public void joinGroup(JSONObject extraJson, String groupId) {
        try {
            GroupCreateInfo groupCreateInfo = DemoContext.getInstance().getOneResult(groupId);
            String array = null;
            array = extraJson.getString("data");
            JSONArray jsonArray = new JSONArray(array);
            if (groupCreateInfo != null) {
                String result = groupCreateInfo.getGourpMembers();
                int groupAmount = groupCreateInfo.getNumber();
                for (int i = 0; i < jsonArray.length(); i++) {
                    result = StringUtilSub.addNewMemberUuid(result, jsonArray.getString(i));
                    groupAmount++;
                    groupCreateInfo.setGourpMembers(result);
                }
                DemoContext.getInstance().updateGroupInfoById(groupId, String.valueOf(groupAmount), DemoContext.STATE3);
                DemoContext.getInstance().updateGroupInfoById(groupId, groupCreateInfo);
            } else {
                HttpMethods.getInstance().fetchGroupById(groupId, new GroupInfoSubscriber());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void editGroup(JSONObject extraJson, String groupId) {
        try {
            String name = null;
            name = extraJson.getString("data");
            GroupCreateInfo groupCreateInfo = DemoContext.getInstance().getOneResult(groupId);
            if (groupCreateInfo != null) {
                String uri = groupCreateInfo.getPortraitUri();
                DemoContext.getInstance().updateGroupInfoById(groupId, name, DemoContext.STATE2);
                EventBus.getDefault().post(new EventModelObject(name));
                refreshGroupInfo(new Group(groupId, name, Uri.parse(uri)));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //新退群逻辑
    private void quitGroupNew(final Conversation.ConversationType conversationType, final String targetId, JSONObject extraJson, final String groupId) {
        try {
            final String userId = extraJson.getString("data");
            final String createUserId = extraJson.optString("create_user_id", "");
            final QuitGroupModel quitGroupModel = new QuitGroupModel();
            quitGroupModel.setGroupId(groupId);
            quitGroupModel.setUserId(userId);
            final GroupCreateInfo groupCreateInfo = DemoContext.getInstance().getOneResult(groupId);
            //查询群组是否存在
            if (groupCreateInfo != null) {
                //是不是我
                if (StringUtilSub.judgeSame(userId, mySharedPreferences.getString("uuid", ""))) {
                    //是我
                    deleteGroup(userId, groupId);
                    RongIM.getInstance().clearMessages(conversationType, targetId);           //清除聊天记录
                } else {
                    //不是我
                    deleteMember(userId, createUserId, groupCreateInfo);
                    EventBus.getDefault().post(quitGroupModel);      //更新群详情界面人数
                }
            } else {
                RongIM.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
                    @Override
                    public void onSuccess(List<Conversation> conversations) {
                        if (conversations == null)
                            return;
                        Iterator iterator = conversations.iterator();
                        while (iterator.hasNext()) {
                            if (((Conversation) iterator.next()).getTargetId().equals(targetId)) {
                                //是不是我
                                if (StringUtilSub.judgeSame(userId, mySharedPreferences.getString("uuid", ""))) {
                                    Log.e("conversation", "删除的是我");
                                    //是我
                                    deleteGroup(userId, groupId);
                                    RongIM.getInstance().clearMessages(conversationType, targetId);           //清除聊天记录
                                } else {
                                    if (databaseUtil.findGroupById(groupId) == null) {
                                        new Handler().postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                GroupCreateInfo groupCreateInfo1 = databaseUtil.findGroupById(groupId);
                                                if (groupCreateInfo1 != null) {
                                                    deleteMember(userId, createUserId, groupCreateInfo1);
                                                } else {
                                                    Log.e("groupCreateInfo1", "is null");
                                                }
                                            }
                                        }, 3000);
                                    }
                                    EventBus.getDefault().post(quitGroupModel);      //更新群详情界面人数
                                }
                                break;
                            }
                        }
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {

                    }
                });
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //删除群成员
    private void deleteMember(String userId, String newCreateUserId, GroupCreateInfo groupCreateInfo) {
        if (!newCreateUserId.equals(groupCreateInfo.getCreate_user_id())) {
            groupCreateInfo.setCreate_user_id(newCreateUserId);
        }
        String newmembers = StringUtilSub.removeOldMemberUuid(
                groupCreateInfo.getGourpMembers(), userId);
        groupCreateInfo.setGourpMembers(newmembers);
        DemoContext.getInstance().updateGroupInfoById(groupCreateInfo.getId(), groupCreateInfo);
    }

    //删除群
    private void deleteGroup(String userId, String groupId) {
        //后续修改此处
        Map<String, Group> groupMap = DemoContext.getInstance().getGroupMap();
        List<GroupCreateInfo> mResultList = DemoContext.getInstance().getResult();
        List<GroupCreateInfo> newResultList = new ArrayList<>();
        if (groupMap != null && mResultList != null) {
            groupMap.remove(groupId);
            for (GroupCreateInfo groupCI : mResultList) {
                if (!groupCI.getId().equals(groupId)) {
                    newResultList.add(groupCI);
                }
            }
            DemoContext.getInstance().setGroupMap(groupMap);                //清除内存该群组信息
            DemoContext.getInstance().setResult(newResultList);             //清除内存该群组信息
            databaseUtil.delateGroup(groupId);                              //清除数据库该群组信息
        }
        RongIM.getInstance().getRongIMClient().quitGroup(groupId, new RongIMClient.OperationCallback() {
            @Override
            public void onSuccess() {
                if (DemoContext.getInstance().getGroupMap() != null)
                    RongContext.getInstance().getEventBus().post(new Event.SyncGroupEvent(
                            new ArrayList<Group>(DemoContext.getInstance().getGroupMap().values())));
                EventBus.getDefault().post(new YspEvent.ConnectEvent());                  //当前完成了消息未读数量的刷新 和 刷新会话列表
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                Log.d(TAG, "-----------QUIT EORROR");
            }
        });
        //删除群成员
        ClearGroupNumber clearGroupNumber = new ClearGroupNumber();
        clearGroupNumber.setUserId(userId);
        EventBus.getDefault().post(clearGroupNumber);
    }
}
